//
//  AppDelegate.m
//  AvatarShow
//
//  Created by xunruiIOS on 2021/4/27.
//

#import "AppDelegate.h"
#import <UMCommonLog/UMCommonLogManager.h>
#import "ASCommentModel.h"
#import <UMCommon/UMConfigure.h>
//#import <UMPush/UMessage.h>
#import "ASHomeApi.h"
#import "ASGuideViewController.h"

@interface AppDelegate ()

@property (assign, nonatomic) BOOL hasNoData;               ///是否进入过无网络状态

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [self loadNetTimeData:^(BOOL hasSucceed) {
        
    }];
    [self createUMeng];
    [self seetingNavBarStyle];
    [self showWindow];
    [self loadNetState];
//    [WXApi registerApp:WX_APPID universalLink:@"https://applefile.bizhijingling.com/"];
//    [WXApi startLogByLevel:WXLogLevelDetail logBlock:^(NSString * _Nonnull log) {
//        FELog(@"log=======%@",log);
//    }];
    [ASTool addUMTongJiKey:@"other" subKey:@"other" titleStr:@"启动页"];
    return YES;
}


///获取当前网络状态
-(void)loadNetState{
    // 1.获得网络监控的管理者
    AFNetworkReachabilityManager *manager =  [AFNetworkReachabilityManager sharedManager];
    // 2.设置网络状态改变后的处理
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 当网络状态改变了, 就会调用这个block
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: // 未知网络
            self.hasNoData = YES;
            break;
        case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
            self.hasNoData = YES;
            break;
        default:
            if (self.hasNoData) {
                [self loadNetTimeData:^(BOOL hasSucceed) {
                }];
            }
            break;
        }
    }];
    // 3.开始监控
    [manager startMonitoring];
}


/// 加载window
- (void)showWindow{
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.window setBackgroundColor:BACKGROUND_COLOR];
    ASTabBarController *rootVC = [[ASTabBarController alloc]init];
    self.tabBar = rootVC;
        
//    [self showLoadPopupView];
    [self.window setRootViewController:rootVC];
    [self.window makeKeyAndVisible];
    
    
    ///用户协议弹框
    NSNumber *num = [[NSUserDefaults standardUserDefaults]objectForKey:@"AGREEPROTOCOL"];
    if (num.boolValue == NO) {
        ASGuideViewController *guVC = [[ASGuideViewController alloc]init];
        UINavigationController *suNav = [[UINavigationController alloc]initWithRootViewController:guVC];
        [self.window setRootViewController:suNav];
    }
}

- (void)seetingNavBarStyle{
    if (@available(iOS 13.0, *)) {
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDarkContent;
    } else {
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;//黑色
    }

    [[UINavigationBar appearance]setTintColor:[UIColor colorWithHexString:@"808080"]];
    [[UINavigationBar appearance]setBarTintColor:MAIN_NAV_COLOR];                   //导航栏颜色
    [[UINavigationBar appearance]setBackIndicatorImage:[UIImage imageNamed:@"icon_back_gray"]];
    [[UINavigationBar appearance]setBackIndicatorTransitionMaskImage:[UIImage imageNamed:@"icon_back_gray"]];
    [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor blackColor]}forState:UIControlStateNormal];
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"1a1a1a"]}];

    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(-100, 0)
                                                         forBarMetrics:UIBarMetricsDefault];
//    [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} forState:UIControlStateNormal];

    //导航栏底部横线
    UIColor *imageColor = [UIColor colorWithHexString:@"#F5F5F5"];
    UIImage *image = [UIImage imageWithColor:imageColor size:CGSizeMake(SCREEN_WIDTH, 0.5)];
    [[UINavigationBar appearance]setShadowImage:image];
}

/// 加载服务端时间
- (void)loadNetTimeData:(void(^)(BOOL hasSucceed))loadFinsh{
    [ASHomeApi updateNetTimeCompletion:^(ASBaseModel *  _Nonnull result) {
        if (result.state.integerValue == 1) {
            //获取本地的时间戳
            NSString *timeStr = [[NSDate date] stringWithFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSInteger timeInt = [ASTool timeSwitchTimestamp:timeStr andFormatter:@"yyyy-MM-dd HH:mm:ss"];
            NSInteger netTime = result.msg.integerValue;
            //计算两个时间戳的时间差
            int timeInterval = [ASTool compareTwoTime:timeInt time2:netTime];
            if ((abs(timeInterval)) >= 5) {
                [[NSUserDefaults standardUserDefaults]setObject:[NSNumber numberWithInt:timeInterval] forKey:TIME_INTERVAL];
            }else{
                [[NSUserDefaults standardUserDefaults]setObject:[NSNumber numberWithInt:0] forKey:TIME_INTERVAL];
            }
//            [self loadAdvData];
        }else if (result.state.integerValue == 401) {
            [[ASUserManager sharedManger]removeUserData];
            [self loadNetTimeData:loadFinsh];
        }
        if (loadFinsh) {
            loadFinsh(YES);
        }
    } failure:^(NSError * _Nonnull error) {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"LoadAdvertisingSucceed" object:nil];
    }];
}

///加载全局推荐数据
- (void)loadAdvData{
    [ASHomeApi loadCommendCompletion:^(ASCommentModel *  _Nonnull result) {
//        if (result.state.intValue == 1) {
//            NSString * temp  = NSTemporaryDirectory();
//            NSString * filePath = [temp stringByAppendingPathComponent:COMMENTLISTKEY];
//            [NSKeyedArchiver archiveRootObject:result toFile:filePath];
//            [[NSNotificationCenter defaultCenter]postNotificationName:@"LoadAdvertisingSucceed" object:nil];
//        }else{
//            [[NSNotificationCenter defaultCenter]postNotificationName:@"LoadAdvertisingSucceed" object:nil];
//        }
        
//        NSMutableArray *advArr = [NSMutableArray new];
//        NSMutableArray *advHeadArr = [NSMutableArray new];
//        NSMutableArray *advHeadArr2 = [NSMutableArray new];
//        for (int x = 0; x < result.poster_10.count; x++) {
//            DFShowAdData *dd = result.poster_10[x];
//            NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dd];
//            [advHeadArr addObject:data];
//        }
//        for (int x = 0; x < result.poster_12.count; x++) {
//            DFShowAdData *dd = result.poster_12[x];
//            NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dd];
//            [advHeadArr2 addObject:data];
//        }
//        for (int x = 0; x < result.ad_postion_list.count; x++) {
//            DFADPostionData *dd = result.ad_postion_list[x];
//            NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dd];
//            [advArr addObject:data];
//        }
//        [[NSUserDefaults standardUserDefaults]setObject:advArr forKey:@"ad_postion_list"];
//        [[NSUserDefaults standardUserDefaults]setObject:advHeadArr forKey:@"poster_10"];
//        [[NSUserDefaults standardUserDefaults]setObject:advHeadArr2 forKey:@"poster_12"];
//        [[NSUserDefaults standardUserDefaults]synchronize];
//        [[NSNotificationCenter defaultCenter]postNotificationName:@"LoadAdvertisingSucceed" object:nil];
    } failure:^(NSError * _Nonnull error) {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"LoadAdvertisingSucceed" object:nil];
    }];
}

/// 初始化友盟
- (void)createUMeng{
    //开发者需要显式的调用此函数，日志系统才能工作
    [UMCommonLogManager setUpUMCommonLogManager];
    [UMConfigure initWithAppkey:UMENG_KEY channel:@"App Store"];
    [UMConfigure setLogEnabled:YES];

     // Push's basic setting
//    UMessageRegisterEntity * entity = [[UMessageRegisterEntity alloc] init];
    //type是对推送的几个参数的选择，可以选择一个或者多个。默认是三个全部打开，即：声音，弹窗，角标
//    entity.types = UMessageAuthorizationOptionBadge|UMessageAuthorizationOptionAlert;
    FELog(@"asdfsadfasdf");
}



#pragma mark - UISceneSession lifecycle
//iOS10新增：处理前台收到通知的代理方法
//-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
//    NSDictionary * userInfo = notification.request.content.userInfo;
//    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
//        //应用处于前台时的远程推送接受
//        //关闭U-Push自带的弹出框
//        [UMessage setAutoAlert:NO];
//        //必须加这句代码
//        [UMessage didReceiveRemoteNotification:userInfo];
//        
//    }else{
//        //应用处于前台时的本地推送接受
//    }
//    //当应用处于前台时提示设置，需要哪个可以设置哪一个
//    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
//}

////iOS10新增：处理后台点击通知的代理方法
//-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler{
//    NSDictionary * userInfo = response.notification.request.content.userInfo;
//    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
//        //应用处于后台时的远程推送接受
//        //必须加这句代码
//        [UMessage didReceiveRemoteNotification:userInfo];
//        
//    }else{
//        //应用处于后台时的本地推送接受
//    }
//}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

//控制旋转方向
-  (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window  {
    return UIInterfaceOrientationMaskPortrait;
}


//#define __IPHONE_10_0    100000
#if __IPHONE_OS_VERSION_MAX_ALLOWED > 100000
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
    return YES;

}
    
- (void)application:(UIApplication *)application handleIntent:(nonnull INIntent *)intent completionHandler:(nonnull void (^)(INIntentResponse * _Nonnull))completionHandler{}
#endif

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    return YES;

}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    return YES;

}

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler{
    NSURL *url = userActivity.webpageURL;
    return YES;
}



@end
